using System.Reflection.Metadata;
using System.Runtime.CompilerServices;
using Microsoft.EntityFrameworkCore;
using Project_Schedule.Configures;
using Project_Schedule.Domain.Receptionist.com.core.dto;
using Project_Schedule.Domain.Receptionist.com.core.Interface;
using Project_Schedule.Domain.Request;
using Project_Schedule.Model;
using Project_Schedule.Model.EntitiesHelper;

namespace Project_Schedule.Domain.Receptionist.com.core.Service;

public class System_LoginService : ISystemLogin
{
    public async Task<JRequest> Login(LoginUser dto)
    {
        try
        {
            await using var db = new DataDbContext();
            var info = await db.SystemUsers?.FirstOrDefaultAsync(e =>
                e.Account == dto.Account);
            if (info is null) throw new Exception("账户不存在");
            if (RsaEncryptUtil.RSADecrypt(info.Password) != dto.Password) throw new Exception("密码错误");
            if (info.IsUsed != System_Audit_Status_Enum.Using) throw new Exception("账户处于不可用状态");
            if (info.Status == Schedule_User_State_Enum.Out) throw new Exception("离职账户不可登陆");

            return JRequest.Ok(info);
        }
        catch (Exception exception)
        {
            _logHelper.LogError(exception);
            return JRequest.Ok(false, false, exception.Message);
        }
    }

    private readonly INLogHelper _logHelper;

    public System_LoginService(INLogHelper logHelper)
    {
        _logHelper = logHelper;
    }
}